# -*- coding:UTF-8 -*-

import pymysql
import logging
from src.bridge.getconfdata import ConfData

logging.basicConfig(filename="./log/getdata.log", filemode='w', format='%(asctime)s : %(levelname)s : %(message)s',
                    level=logging.DEBUG)


class SelectData:
    def __init__(self):
        self.cf = ConfData()
        self.conn = pymysql.connect(host=self.cf.get_one_value(section='db', key='local'),
                                    user=self.cf.get_one_value(section='db', key='user'),
                                    password=self.cf.get_one_value(section='db', key='passwd'),  # pxvffg2AgJr
                                    database=self.cf.get_one_value(section='db', key='dbname'),
                                    port=int(self.cf.get_one_value(section='db', key='port'))
                                    )
        self.conr = self.conn.cursor()

    def select_data(self, table, showcoloum="*", condition="1=1", limit=200):
        sql = "select {} from {} where {} limit {};".format(showcoloum, table, condition, limit)
        logging.info(sql)
        try:
            self.conr.execute(sql)
            data = self.conr.fetchall()
            logging.info(data)
            return data
        except BaseException as e:
            logging.error(e)

    def select_history_action(self, user, day):
        sql = "SELECT a.date,a.objectType,a.objectID,h.old, h.new " \
              "from zt_history h " \
              "LEFT JOIN zt_action a ON h.action = a.id  " \
              "WHERE a.actor = '{}' AND h.field ='status' AND h.new in('done','closed','cancel') " \
              "AND a.date >'{}' ORDER BY a.date desc;".format(user, str(day))
        logging.info(sql)
        try:
            self.conr.execute(sql)
            data = self.conr.fetchall()
            logging.info(data)
            return data
        except BaseException as e:
            logging.error(e)

